<?php

namespace lc\wechat\auth\Gateways;

use lc\cache\memcache\MemCacheToken;
use lc\helpers\Curl;
use lc\Preinstall;

class Platform extends Base
{
    private $appId;
    private $platformAppId;
    private $platformSecret;

    public function __construct()
    {
        parent::__construct();

        $this->appId = $this->config['appid'];
        if (!empty($this->config['pt_appid'])) {
            $this->platformAppId  = $this->config['pt_appid'];
            $this->platformSecret = $this->config['pt_secret'];
        } else {
            $ptConf = PreInstall::get('wechat');
            $this->platformAppId  = $ptConf[$this->config['pt_id']]['pt_appid'];
            $this->platformSecret = $ptConf[$this->config['pt_id']]['pt_secret'];
        }
    }

    public function setAppId(string $appId)
    {
        $this->appId = $appId;
    }

    /**
     * @link    第一步 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Official_Accounts/official_account_website_authorization.html
     * @desc    获取授权地址
     * @param   string      $scope 授权方式 snsapi_base|snsapi_userinfo
     * @param   string|null $redirect
     * @return  string
     */
    public function authUrl(string $scope = 'snsapi_userinfo', string $redirect = null): string
    {
        $redirect = $redirect ? $redirect : "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
        $query = http_build_query([
            'appid'             => $this->appId,
            'redirect_uri'      => $redirect,
            'response_type'     => 'code',
            'scope'             => $scope,
            'state'             => 1,
            'component_appid'   => $this->platformAppId
        ]);

        return "https://open.weixin.qq.com/connect/oauth2/authorize?{$query}#wechat_redirect";
    }

    /**
     * @link    第二步 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Official_Accounts/official_account_website_authorization.html
     * @desc    使用授权code换取openid
     * @param   string $code
     * @return  mixed
     */
    public function code2Openid(string $code): array
    {
        $cache = new MemCacheToken();
        $token = $cache->getPtToken($this->platformAppId);

        $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token';
        $res = Curl::requestCurl($url, 'GET', [], http_build_query([
            'appid'             => $this->appId,
            'code'              => $code,
            'grant_type'        => 'authorization_code',
            'component_appid'   => $this->platformAppId,
            'component_access_token' => $token
        ]));

        return $res ? json_decode($res, true) : false;
    }

    /**
     * @link    第四步 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Before_Develop/Official_Accounts/official_account_website_authorization.html
     * @desc    获取用户基础信息
     * @param   string  $accessToken
     * @param   string  $openid
     * @return  array
     */
    public function userSimpleInfo(string $accessToken, string $openid): array
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo';
        $res = Curl::requestCurl($url, 'GET', [], http_build_query([
            'access_token'  => $accessToken,
            'openid'        => $openid,
            'lang'          => 'zh_CN',
        ]));

        return $res ? json_decode($res, true) : [];
    }

    /**
     * @link    https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId
     * @desc    获取用户详细信息
     * @param   string $openid
     * @return  array
     */
    public function userDetailInfo(string $openid): array
    {
        $cache = new MemCacheToken();
        $token = $cache->getTokenByPt($this->platformAppId, $this->appId);

        $url = 'https://api.weixin.qq.com/cgi-bin/user/info';
        $res = Curl::requestCurl($url, 'GET', [], http_build_query([
            'access_token'  => $token->token,
            'openid'        => $openid,
            'lang'          => 'zh_CN',
        ]));

        return $res ? json_decode($res, true) : [];
    }

    /**
     * @desc    获取 JSAPI TICKET
     * @return  string
     */
    public function jsApiTicket()
    {
        $cache = new MemCacheToken();

        return $cache->getJsTicket($this->appId);
    }

    /**
     * 获取token
     *
     * @return mixed
     */
    public function accessToken()
    {
        $cache = new MemCacheToken();
        $token = $cache->getTokenByPt($this->platformAppId, $this->appId);
        return $token->token;
    }
}
